package com.meiyuetao.myt.job;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import lab.s2jh.core.pagination.GroupPropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter.MatchType;
import lab.s2jh.crawl.filter.ParseFilter;
import lab.s2jh.crawl.service.CrawlService;
import lab.s2jh.ctx.DynamicConfigService;
import lab.s2jh.ctx.FreemarkerService;
import lab.s2jh.ctx.MailService;
import lab.s2jh.schedule.BaseQuartzJobBean;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.meiyuetao.myt.crawl.filter.AbstractCommodityParseFilter;
import com.meiyuetao.myt.md.entity.Commodity;
import com.meiyuetao.myt.md.service.CommodityService;

public class MytCommodityPriceCompareHourlyJob extends BaseQuartzJobBean {
    private final static Logger logger = LoggerFactory.getLogger(MytCommodityPriceCompareHourlyJob.class);

    @Override
    protected void executeInternalBiz(JobExecutionContext context) {
        logger.debug("MytCommodityPriceCompareHourlyJob executing...");

        CommodityService commodityService = this.getSpringBean(CommodityService.class);
        CrawlService crawlService = this.getSpringBean(CrawlService.class);
        DynamicConfigService dynamicConfigService = this.getSpringBean(DynamicConfigService.class);
        FreemarkerService freemarkerService = this.getSpringBean(FreemarkerService.class);
        Map<String, List<Map<String, String>>> resultMap = new HashMap<String, List<Map<String, String>>>();
        Map<String, String> resultLittleMap;

        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();

        groupPropertyFilter.append(new PropertyFilter(MatchType.NU, "priceCompareUrl", false));
        List<Commodity> commodities = commodityService.findByFilters(groupPropertyFilter);
        List<Map<String, String>> resultList = new ArrayList<Map<String, String>>();
        String rate = dynamicConfigService.getString("cfg.commodity.price.compare.rate", "");
        BigDecimal compareRate = new BigDecimal(rate);
        if (CollectionUtils.isNotEmpty(commodities)) {
            for (Commodity commodity : commodities) {
                if (StringUtils.isBlank(commodity.getPriceCompareUrl())) {
                    continue;
                }
                List<ParseFilter> parseFilters = crawlService.getParseFilters();
                Map<String, Object> simpleData = null;
                for (ParseFilter parseFilter : parseFilters) {
                    if (parseFilter instanceof AbstractCommodityParseFilter) {
                        AbstractCommodityParseFilter abstractCommodityParseFilter = (AbstractCommodityParseFilter) parseFilter;
                        simpleData = abstractCommodityParseFilter.parseSimpleData(commodity.getPriceCompareUrl());
                        if (simpleData != null && StringUtils.isNotBlank((String) simpleData.get("salePrice"))) {
                            BigDecimal salePrice = new BigDecimal((String) simpleData.get("salePrice"));
                            BigDecimal priceCompareRate = commodity.getPriceCompareRate();
                            if (priceCompareRate != null && priceCompareRate.compareTo(BigDecimal.ZERO) == 1) {
                                compareRate = priceCompareRate;
                            }
                            if (salePrice.compareTo(commodity.getPrice().multiply(new BigDecimal(1).add(compareRate))) >= 0
                                    || salePrice.compareTo(commodity.getPrice().multiply(new BigDecimal(1).subtract(compareRate))) <= 0) {
                                resultLittleMap = new LinkedHashMap<String, String>();
                                resultLittleMap.put("商品编码：", commodity.getSku());
                                resultLittleMap.put("商品名称", commodity.getTitle());
                                resultLittleMap.put("商品状态：", commodity.getCommodityStatus().name());
                                resultLittleMap.put("商品价格：", String.valueOf(commodity.getPrice()));
                                resultLittleMap.put("比价价格", String.valueOf(salePrice));
                                resultLittleMap.put("偏移报警比率：", String.valueOf(compareRate));
                                resultLittleMap.put("比价链接", commodity.getPriceCompareUrl());
                                resultList.add(resultLittleMap);

                            }
                        }
                    }
                }

            }
        }
        if (resultList.size() > 0) {
            resultMap.put("商品价格监控提醒", resultList);
        }
        String emailHTML = null;
        String emailToList = dynamicConfigService.getString("cfg.commodity.price.compare.email", "");
        // 发送通知邮件
        logger.debug("send Email……" + resultMap.size() + "," + StringUtils.isNotBlank(emailToList));
        if (resultMap.size() > 0 && StringUtils.isNotBlank(emailToList)) {
            logger.debug("send Email……");
            String[] emails = emailToList.replace("，", ",").split(",");

            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("resultMap", resultMap);
            emailHTML = freemarkerService.processTemplateByFileName("MYT_COMMODITY_PRICE_COMPARE_NOTIFY", dataMap);
            MailService mailService = this.getSpringBean(MailService.class);
            mailService.sendHtmlMail("商品比价监控", emailHTML, false, emails);

        }

        context.setResult(emailHTML);
    }
}
